from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions
from django.db.models import Count, Sum
from orders.models import Order
from products.models import Product
from delivery.models import Delivery
from users.models import User

class DashboardStatsView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        user = request.user
        stats = {}

        # 根据用户角色返回不同的统计数据
        if user.role == 'admin':
            # 管理员可以看到所有统计数据
            stats = {
                'total_users': User.objects.count(),
                'total_orders': Order.objects.count(),
                'total_products': Product.objects.count(),
                'total_deliveries': Delivery.objects.count(),
                'pending_orders': Order.objects.filter(status='pending').count(),
                'low_stock_products': Product.objects.filter(stock__lt=10).count(),
            }
        elif user.role == 'salesman':
            # 销售员可以看到订单相关统计
            stats = {
                'total_orders': Order.objects.count(),
                'pending_orders': Order.objects.filter(status='pending').count(),
                'completed_orders': Order.objects.filter(status='completed').count(),
            }
        elif user.role == 'purchaser':
            # 采购员可以看到库存相关统计
            stats = {
                'total_products': Product.objects.count(),
                'low_stock_products': Product.objects.filter(stock__lt=10).count(),
            }
        elif user.role == 'deliveryman':
            # 配送员可以看到配送相关统计
            stats = {
                'total_deliveries': Delivery.objects.count(),
                'pending_deliveries': Delivery.objects.filter(status='pending').count(),
            }
        elif user.role == 'customer':
            # 客户可以看到自己的订单统计
            stats = {
                'total_orders': Order.objects.filter(customer=user).count(),
                'pending_orders': Order.objects.filter(customer=user, status='pending').count(),
                'completed_orders': Order.objects.filter(customer=user, status='completed').count(),
            }

        return Response(stats) 